/**
 * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jboot.component.metric.reporter.influxdb;

import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ScheduledReporter;
import io.jboot.Jboot;
import io.jboot.component.metric.JbootMetricReporter;

import java.util.concurrent.TimeUnit;

import io.jboot.utils.StringUtils;
import metrics_influxdb.HttpInfluxdbProtocol;

/**
 * @author shaojava 邵文长 （shaojava@sina.com）
 * @version V1.1
 * @Package io.jboot.component.metrics.reporter.influxdb
 */
public class InfluxdbReporter implements JbootMetricReporter {

    @Override
    public void report(MetricRegistry metricRegistry) {

        JbootMetricsInfluxdbReporterConfig config = Jboot.config(JbootMetricsInfluxdbReporterConfig.class);

        if (StringUtils.isBlank(config.getHost())) {
            throw new NullPointerException("influxdb reporter host must not be null, please config jboot.metrics.reporter.influxdb.host in you properties.");
        }
        if (config.getPort() == null) {
            throw new NullPointerException("influxdb reporter port must not be null, please config jboot.metrics.reporter.influxdb.port in you properties.");
        }
        if (config.getUsername() == null) {
            throw new NullPointerException("influxdb reporter username must not be null, please config jboot.metrics.reporter.influxdb.username in you properties.");
        }
        if (config.getDatabase() == null) {
            throw new NullPointerException("influxdb reporter database must not be null, please config jboot.metrics.reporter.influxdb.database in you properties.");
        }

        final ScheduledReporter reporter = metrics_influxdb.InfluxdbReporter.forRegistry(metricRegistry)
                .protocol(new HttpInfluxdbProtocol("http",config.getHost(), config.getPort(), config.getUsername(), config.getPassword(), config.getDatabase()))
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .filter(MetricFilter.ALL)
                .skipIdleMetrics(false)
                .build();
        reporter.start(10, TimeUnit.SECONDS);
    }

}
